package com.zx.tradeclient.ctrl.index1;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.zx.base.lazylist.ImageLoader;
import com.zx.base.util.URLHelper;
import com.zx.tradeclient.R;
import com.zx.tradeclient.app.TradeApp;

public class TopHead {
	private ViewPager viewPager; // android-support-v4中的滑动组件
	private List<ImageView> imageViews; // 滑动的图片集合

	private String[] titles; // 图片标题
	private int[] imageResId; // 图片ID
	private List<View> dots; // 图片标题正文的那些点
	private int currentItem = 0; // 当前图片的索引号

	public TextView tv_title;
	public List<Map<String, String>> listData;
	private MyAdapter adapter;
	private MyPageChangeListener pageChangeListener;

	// An ExecutorService that can schedule commands to run after a given delay,
	// or to execute periodically.
	private ScheduledExecutorService scheduledExecutorService;
	private ImageLoader imageLoader;
	private Context context;

	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
		};
	};

	public TopHead(Context context) {
		this.context = context;
		imageResId = new int[10];
		titles = new String[imageResId.length];
		imageViews = new ArrayList<ImageView>();

		dots = new ArrayList<View>();
		listData = new ArrayList<Map<String, String>>();

		// 初始化图片资源
		for (int i = 0; i < imageResId.length; i++) {
			ImageView imageView = new ImageView(context);
			// imageView.setImageResource(imageResId[i]);
			imageView.setScaleType(ScaleType.CENTER_CROP);
			imageViews.add(imageView);
		}
		imageLoader = ((TradeApp) context.getApplicationContext()).imageLoader;
		adapter = new MyAdapter();
		pageChangeListener = new MyPageChangeListener();
	}

	public void init(View view) {
		dots.clear();
		dots.add(view.findViewById(R.id.news_top_dot0));
		dots.add(view.findViewById(R.id.news_top_dot1));
		dots.add(view.findViewById(R.id.news_top_dot2));
		dots.add(view.findViewById(R.id.news_top_dot3));
		dots.add(view.findViewById(R.id.news_top_dot4));
		dots.add(view.findViewById(R.id.news_top_dot5));
		dots.add(view.findViewById(R.id.news_top_dot6));
		dots.add(view.findViewById(R.id.news_top_dot7));
		dots.add(view.findViewById(R.id.news_top_dot8));
		dots.add(view.findViewById(R.id.news_top_dot9));

		tv_title = (TextView) view.findViewById(R.id.news_top_title);

		viewPager = (ViewPager) view.findViewById(R.id.news_top_vp);
		viewPager.setAdapter(adapter);// 设置填充ViewPager页面的适配器
		// 设置一个监听器，当ViewPager中的页面改变时调用
		viewPager.setOnPageChangeListener(pageChangeListener);
	}

	public void onStart() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 当Activity显示出来后，每两秒钟切换一次图片显示
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 3, TimeUnit.SECONDS);

	}

	public void onStop() {
		// 当Activity不可见的时候停止切换
		scheduledExecutorService.shutdown();
	}

	public void onUpdate() {
		adapter.notifyDataSetChanged();
		tv_title.setText(listData.get(0).get("title"));
		for (int i = listData.size(); i < 10; i++) {
			dots.get(i).setVisibility(View.GONE);
		}
	}

	/**
	 * 换行切换任务
	 * 
	 * @author Administrator
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (viewPager) {
				if (listData.size() != 0) {
					currentItem = (currentItem + 1) % listData.size();
				} else {
					currentItem = (currentItem + 1) % imageViews.size();
				}

				handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
			}
		}

	}

	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			currentItem = position;
			tv_title.setText(titles[position]);
			dots.get(oldPosition).setBackgroundResource(R.drawable.news_normal);
			dots.get(position).setBackgroundResource(R.drawable.news_focused);
			oldPosition = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	/**
	 * 填充ViewPager页面的适配器
	 * 
	 * @author Administrator
	 * 
	 */
	class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return listData.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			Map<String, String> map = listData.get(arg1);
			String imgPath = map.get("imgPath");
			String title = map.get("title");
			final String id = map.get("id");

			imageLoader.DisplayImage(URLHelper.mPrefixImg + "/" + imgPath, imageViews.get(arg1), R.drawable.default_middle);
			titles[arg1] = title;
			// remove parent
			ViewParent parent = imageViews.get(arg1).getParent();
			if (parent != null) {
				((ViewPager) parent).removeView(imageViews.get(arg1));
			}
			// add view
			imageViews.get(arg1).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, DetailActivity.class);
					intent.putExtra("newsId", id);
					context.startActivity(intent);
				}
			});
			((ViewPager) arg0).addView(imageViews.get(arg1));
			return imageViews.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}
}
